package com.ruoyi.common.utils;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zuowei
 * @version 1.0
 * @date 2021-06-18 11:06
 */
public class ffmpegUtils {


    /**
     * 获取上传路径
     * @return
     */
    public static String getFilePath() {
        String path = RuoYiConfig.getUploadPath() + "/" + DateUtils.datePath() + "/";
        File filePath = new File(path);
        if (!filePath.exists()) {
            filePath.mkdir();
        }

        return path;
    }

    public static Boolean FileIsExist(String path){
        File file = new File(path);
        return file.exists();
    }


    /**
     * 从视频中提取音频
     *
     * @param videoPath 视频路径
     * @param AudioType 音频格式
     * @return
     */
    public static String getAudioFromVideo(String videoPath, String AudioType) {
        String audioPath = getFilePath();
        String audioName = IdUtils.simpleUUID() + "." + AudioType;
        String audioFile = audioPath + audioName;
        String commStr = " -i " + videoPath + " -f " + AudioType + " " + audioFile;
        exec(commStr);
        if(FileIsExist(audioFile)){
            return audioFile;
        }else {
            return "";
        }

    }

    /**
     * 给视频添加字幕
     * @param videoPath 原视频
     * @param srtfilePath 字幕文件
     * @return
     */
    public static String AddSubtitlesForVideo(String videoPath,String srtfilePath){
        String targetFile = getFilePath() + IdUtils.simpleUUID() + videoPath.substring(videoPath.lastIndexOf("."));
        //String commStr = " -i " + videoPath + " -vf subtitles=" + srtfilePath + " " + targetFile;
        List<String> command = new ArrayList<String>();
        command.add(RuoYiConfig.getFfpemgPath());
        command.add("-i");
        command.add(videoPath);
        command.add("-vf");
        command.add("subtitles="+srtfilePath.replace("D:","D\\\\:"));
        command.add(targetFile);
        Object result = execCommand(command);
        if(FileIsExist(targetFile) && StringUtils.isNotEmpty(result+"")){
            return targetFile;
        }else {
            return "";
        }
    }


    public static File createFile(String fileName, String fileSuffix) {
        String withfileSuffix = RuoYiConfig.getUploadPath() + "/" + fileName;
        if (StringUtils.isNotEmpty(fileSuffix)) {
            withfileSuffix = withfileSuffix + "." + fileSuffix;
        }
        File file = new File(withfileSuffix);
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }


    /**
     * 执行ffmpeg 命令
     *
     * @param cmd
     * @return
     */
    public static Object exec(String cmd) {
        StringBuffer sb = new StringBuffer();
        try {
            //如果指定路径没安装ffmpeg 则不执行
            if(!FileIsExist(RuoYiConfig.getFfpemgPath() )){
                return null;
            }
            String osName = System.getProperty("os.name");
            String cmdStr = "cmd /c " + RuoYiConfig.getFfpemgPath();

            if (osName.contains("Linux")) {
                cmdStr = "/bin/sh -c ";
            }

            String comm = cmdStr + cmd;

            Process process = Runtime.getRuntime().exec(comm);

            process.waitFor();
            LineNumberReader br = new LineNumberReader(new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            process.destroy();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 执行ffmpeg命令
     * @param cmd
     * @return
     */
    public static Object execCommand(List<String> cmd){

        StringBuffer sb = new StringBuffer();
        try {
             String ffpemgPath = RuoYiConfig.getFfpemgPath();
            //如果指定路径没安装ffmpeg 则不执行
            if(!FileIsExist(ffpemgPath)){
                return null;
            }
            //String comm = ffpemgPath + cmd;
            ProcessBuilder builder = new ProcessBuilder();
            //正常信息和错误信息合并输出
            builder.redirectErrorStream(true);
            builder.command(cmd);
            //开始执行命令
            Process process = builder.start();

            //如果你想获取到执行完后的信息，那么下面的代码也是需要的
            String line = "";
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

}
